from flask import current_app,Blueprint,render_template,request,flash,redirect,url_for
from app import login_manager,flask_bcrypt
from flask_login import  login_required,login_user,logout_user
import forms
from backends.User import User


avbd_auth = Blueprint('avbd_auth',__name__,template_folder='templates')


@avbd_auth.route('/login',methods=['GET','POST'])
def login():
    if request.method == "POST" and "email" in request.form:
        email = request.form["email"]
        userObj = User()
        user = userObj.get_by_email_w_password(email)
        if user and  flask_bcrypt.check_password_hash(user.password,request.form['password']) and user.active:
            remember = request.form.get('remember','no') == "yes"
            if login_user(user,remember=remember):
                return redirect(url_for("avbd_app.index"))
            else:
                flash("unable to log you in")
        else:
            flash("Please check your email or password",category='error')
    return render_template("auth/login.html")

@avbd_auth.route("/register",methods=["GET","POST"])
def register():
    registerForm = forms.SignupForm(request.form)
    current_app.logger.info(request.form)
    if request.method == "POST" and registerForm.validate() == False:
        current_app.logger.info(registerForm.errors)
        return "registration error"
    elif request.method == 'POST' and registerForm.validate():
        email = request.form['email']
        password_hash = flask_bcrypt.generate_password_hash(request.form['password'])
        user = User(email,password_hash)
        try:
            user.save()
            if login_user(user,remember=False):
                flash("logged in")
                return redirect('/')
            else:
                flash("unable to log you in")
        except:
            flash("unable to register with that email address")
            current_app.logger.error("error on registration  - possible duplicate emails")

    templateDate = {
        'form':registerForm
    }
    return render_template('auth/register.html',**templateDate)




@avbd_auth.route("/logout")
@login_required
def logout():
    logout_user()
    flash("logged out",category='success')
    return redirect('/login')

@login_manager.unauthorized_handler
def unauthorized_callback():
    return redirect('/login')

@login_manager.user_loader
def load_user(id):
    if id is None:
        redirect('/login')
    user = User()
    user.get_by_id(id)
    if user.is_active:
        return user
    else:
        return None








